package com.citic.topview.app.mobile.controller;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.citic.topview.common.system.entity.AppException;
import com.citic.topview.common.system.entity.User;
import com.citic.topview.common.system.vo.AppExceptionVO;
import com.citic.topview.common.util.DateUtils;
import com.citic.topview.common.vo.AppResultVO;
import com.citic.topview.system.controller.BaseController;
import com.citic.topview.system.service.AppExceptionService;
import com.citic.topview.system.util.ShiroUtils;

@Controller
@RequestMapping("/app/exception")
public class AppExceptionsController extends BaseController{

	@Autowired
	private AppExceptionService appExceptionService;
	
	@RequestMapping("save")
	@ResponseBody
	public AppResultVO<Object> save(@RequestBody AppExceptionVO appExceptionVO, HttpServletRequest request, HttpServletResponse response) {
		try {
			AppException appException = new AppException();
			String createTime = appExceptionVO.getCreateTime();
			if(StringUtils.isNotBlank(createTime)) {
				Date date = DateUtils.parseDate(createTime, "yyyy-MM-dd HH:mm:ss");
				appException.setCreateExceptionTime(date);
			}
			
			User user = ShiroUtils.getUser();
			if(user != null && user.getId() != null) {
				appException.setUserId(user.getId());
			} else {
				appException.setUserId(0L);
			}
			appException.setCode(appExceptionVO.getCode());
			appException.setException(appExceptionVO.getException());
			appException.setMessage(appExceptionVO.getMessage());
			appException.setPhoneInfo(appExceptionVO.getPhoneInfo());
			appException.setVersion(appExceptionVO.getVersion());
			
			appExceptionService.save(appException);
			AppResultVO<Object> resultVO = setResult(AppResultVO.SUCCESS, "保存异常信息成功", null);
			return resultVO;
		} catch (Exception e) {
			logger.error("保存异常信息失败", e);
			AppResultVO<Object> resultVO = setResult(AppResultVO.ERROR, "保存异常信息失败", e.getMessage());
			return resultVO;
		}
	}
}
